//
//  TT_TableViewListViewController.m
//  TalkTalk
//
//  Created by ypj on 2019/3/21.
//  Copyright © 2019 河南浩之岩. All rights reserved.
//

#import "TT_TableViewListViewController.h"
#import "MJRefresh.h"
#import "TableViewCell.h"
#import "ZuLinPrefixHeader.pch"
@interface TT_TableViewListViewController ()
{
    NSTimer *_timer;
    int _interval;
}

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, assign) BOOL isLoadingData;

@end

@implementation TT_TableViewListViewController

#pragma mark - getter and settter
-(UITableViewController *)tableVC{
    if (!_tableVC) {
        
        _tableVC=[[UITableViewController alloc] initWithStyle:UITableViewStyleGrouped];
        [self addChildViewController:_tableVC];
    }
    return _tableVC;
}

- (UITableView *)tableView
{
    if (!_tableView) {
        
        _tableView = self.tableVC.tableView;
        //_tableView.frame=CGRectMake(0, 0, VIEW_WIDTH, VIEW_HEIGHT);
        _tableView.frame = CGRectMake(0, 0, ScreenWidth, self.view.height);

        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.backgroundColor = [UIColor whiteColor];
        
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        
        UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 1)];
        [_tableView setTableHeaderView:headView];
        __weak TT_TableViewListViewController * blockSelf = self;
        //3.1.0版本的MJRefresh下拉刷新更多的block方法
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            if (!blockSelf.isLoadingData) {
                [blockSelf refreshData];
            }
        }];
        _tableView.mj_footer=[MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            if (!blockSelf.isLoadingData) {
                [blockSelf loadMore];
            }
        }];
        [self.view addSubview:_tableView];
    }
    return _tableView;
}


- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
   // [self  loadinghidden];
    
    [_timer setFireDate:[NSDate distantFuture]];
}
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
   // [self loadinghidden];
    
    [_timer setFireDate:[NSDate distantPast]];
}
- (NSMutableArray *)dataSource
{
    if (!_dataSource) {
        
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.tableViewCellClassName = @"TableViewCell";
        self.isLoadingData = NO;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    _interval=5;
    [self.tableView.mj_footer setHidden:YES];
//    if (self.tableViewCellClassName.length > 0) {
//        [self.tableView registerClass:NSClassFromString(self.tableViewCellClassName) forCellReuseIdentifier:[NSClassFromString(self.tableViewCellClassName) description]];
//    }

    if (@available(iOS 11.0, *)){
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {

    }
}

-(void)timer
{
    _interval--;
    if (_interval== 0){
        //[AlertUtil showAlertWithText:@"网络超时，请重新加载"];
        [self stopAnimating];
        [_timer setFireDate:[NSDate distantFuture]];
        _interval = 5;
    }else
    {
        //[_timer setFireDate:[NSDate distantPast]];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (void)refreshData
{
    self.pageIndex = 1;
    self.pageSize  = 20;
    self.isLoadingData = YES;
}

- (void)stopAnimating
{
    [self.tableView.mj_header endRefreshing];
    [self.tableView.mj_footer endRefreshing];
     self.isLoadingData = NO;
}

- (void)loadDataFinished:(NSArray * )items
{
    [self loadDataFinished:items isMore:NO];
}

- (void)loadDataFinished:(NSArray *)items isMore:(BOOL)isMore
{
    [self stopAnimating];
    [self setIsLoadingData:NO];
    if ([items count]) {
        self.pageIndex++;
        [self.dataSource addObjectsFromArray:items];
    }
    
    if (self.dataSource.count) {
        [self.tableView.mj_footer setHidden:NO];
        
        if (isMore) {
            [self.tableView.mj_footer setHidden:NO];
            [self.tableView.mj_footer resetNoMoreData];
        } else {
            [self.tableView.mj_footer setHidden:YES];
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        }
    }else {
        if (_emptyTipViewOrErrorIsTop==YES) {
            [self showTopErrorView:@"搜索无结果"];
        } else {
            [self showEmptyWithIcon:_noSourceImage tips:_titleString];
        }
        [self.tableView.mj_footer setHidden:YES];
    }
    NSLog(@"---------******  %ld",(unsigned long)self.dataSource.count);
    [self.tableView reloadData];
}

- (void)loadDataError:(NSError *)error
{
    NSString * reason= [error localizedFailureReason];
    NSString * description= [error localizedDescription];
    if ([reason isKindOfClass:[NSNull class]]||reason.length<=0) {
        reason= @"";
    }
    if ([description isKindOfClass:[NSNull class]]||description.length<=0) {
        description= @"";
    }
    
    NSString *string = [NSString stringWithFormat:@"%@",description];
    [self showMessage:string];
    [self loadDataFinished:@[]];
    if (!self.dataSource.count) {
        [self showErrorView];
        [self.tableView.mj_footer setHidden:YES];
        
    }
}

- (void)loadMore
{
    self.isLoadingData = YES;
}


- (void)didSelectedItem:(id)selectedItem
{
    
}
#pragma mark - UITableViewDelegate / UITableViewDataSource

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *identitify = [NSClassFromString(self.tableViewCellClassName) description];
    TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identitify];
    if (!cell) {
        cell = [[NSClassFromString(self.tableViewCellClassName) alloc] initWithStyle:UITableViewCellStyleDefault
                                                                     reuseIdentifier:identitify];
    }
    
    if (indexPath.row < self.dataSource.count) {
        
        [cell tableViewCellWithData:[self.dataSource objectAtIndex:indexPath.row] forIndexPath:indexPath];
        [cell removeTopLine];
        
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row >= self.dataSource.count) {
        return [[((TableViewCell *)NSClassFromString(self.tableViewCellClassName)) class] cellHeight];
    }
    return [[((TableViewCell *)NSClassFromString(self.tableViewCellClassName)) class] accordHeight:[self.dataSource objectAtIndex:indexPath.row] forIndexPath:indexPath];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (self.dataSource.count > indexPath.row) {
        [self didSelectedItem:[self.dataSource objectAtIndex:indexPath.row]];
    }
}
-(void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    
}



@end
